package cc.siyecao.uid.database.resposity;

import cc.siyecao.uid.core.resposity.WorkerNodeEntity;
import cc.siyecao.uid.core.resposity.WorkerNodeResposity;
import org.springframework.jdbc.core.JdbcTemplate;


public class WorkerNodeDatabase implements WorkerNodeResposity {

    private static final String GET_WORKER_NODE_BY_HOST_PORT_SQL = "SELECT ID,HOST_NAME,PORT,TYPE,LAUNCH_DATE,MODIFIED,CREATEDFROMWORKER_NODEWHEREHOST_NAME = ? AND PORT = ?";
    private static final String ADD_WORKER_NODE_SQL = "INSERT INTO WORKER_NODE (HOST_NAME,PORT,TYPE,LAUNCH_DATE,MODIFIED,CREATED)VALUES (?,?,?,?,NOW(),NOW())";

    private final JdbcTemplate jdbcTemplate;

    public WorkerNodeDatabase(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * Get {@link WorkerNodeEntity} by node host
     *
     * @param host
     * @param port
     * @return
     */
    @Override
    public WorkerNodeEntity getWorkerNodeByHostPort(String host, String port) {
        return this.jdbcTemplate.queryForObject( GET_WORKER_NODE_BY_HOST_PORT_SQL, (rs, rowNum) -> {
            WorkerNodeEntity entity = new WorkerNodeEntity();
            entity.setId( rs.getLong( "ID" ) );
            entity.setHostName( rs.getString( "HOST_NAME" ) );
            entity.setPort( rs.getString( "PORT" ) );
            entity.setType( rs.getInt( "TYPE" ) );
            entity.setLaunchDateDate( rs.getDate( "LAUNCH_DATE" ) );
            entity.setModified( rs.getTimestamp( "MODIFIED" ) );
            entity.setCreated( rs.getTime( "CREATED" ) );
            return entity;
        }, new String[]{host, port} );
    }

    /**
     * Add {@link WorkerNodeEntity}
     *
     * @param entity
     */
    @Override
    public void addWorkerNode(WorkerNodeEntity entity) {
        this.jdbcTemplate.update( ADD_WORKER_NODE_SQL, entity.getHostName(), entity.getPort(), entity.getType(), entity.getLaunchDate() );
    }

}
